package com.kkd.kkdapp.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;

import org.json.JSONException;
import org.json.JSONObject;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.db.CurUserModel;
import com.kkd.kkdapp.db.app.model.User;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpClient;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.FileUtils;
import com.kkd.kkdapp.utils.ImageUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.view.KKdDialog;
import com.kkd.kkdapp.view.RoundImageView;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/***
 * 
 * @author mty
 * 
 * @Name 个人信息
 * 
 */
public class PersonalInformationActivity extends BaseActivity implements
		OnClickListener {

	private static final int UPDATEHEAD_OK = 1;
	private static final int UPDATEHEAD_NO = 2;
	public static final int SAFE_EXIT_RESULTCODE = 100; // 安全退出结果码
	private static final int NICKNAME_JUMP = 106;
	private RelativeLayout top_img; // 返回键
	private Button safe_exit; // 安全退出
	private TextView phone_tv; // 用户手机号
	private TextView set_nickname; // 昵称
	private RelativeLayout nickname_rl; // 修改昵称
	private RoundImageView portrait_img; // 头像
	private RelativeLayout portrait_rl; // 设置头像
	private KKdDialog ppw; // 设置头像弹窗
	private TextView dimis; // 关闭设置头像弹窗
	private String filePath; // 头像图片url
	private Dialog mDialog; // 头像设置等待弹窗
	private int statusCode;
	private String urserHeadUrl; // 后台返回头像url

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case UPDATEHEAD_OK:
				mDialog.dismiss();
				mDialog.cancel();
				mDialog = null;
				showToast("保存成功");
				AppUtil.makeToastForCustomer(PersonalInformationActivity.this,
						"保存成功");
				ImageLoader.getInstance().displayImage(urserHeadUrl,
						portrait_img);
				break;
			case UPDATEHEAD_NO:
				mDialog.dismiss();
				mDialog.cancel();
				mDialog = null;
				if (statusCode == KkdHttpClient.NO_NET) {
					showToast("网络错误，请稍后重试");
				} else if (statusCode == KkdHttpClient.RESOLUTION_EXCEPTION) {
					showToast("服务异常，请稍后重试");
				} else {
					showToast("服务异常，请稍后重试");
				}
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_personal_information);
		initView();
		setListener();
	}

	/**********
	 * 初始化控件
	 **********/
	public void initView() {
		top_img = (RelativeLayout) this.findViewById(R.id.top_img);
		phone_tv = (TextView) this.findViewById(R.id.phone_tv);
		safe_exit = (Button) this.findViewById(R.id.safe_exit);
		set_nickname = (TextView) this.findViewById(R.id.set_nickname);
		nickname_rl = (RelativeLayout) this.findViewById(R.id.nickname_rl);
		portrait_img = (RoundImageView) this.findViewById(R.id.portrait_img);
		portrait_rl = (RelativeLayout) this.findViewById(R.id.portrait_rl);

	}

	// 注册监听事件
	public void setListener() {
		top_img.setOnClickListener(this);
		safe_exit.setOnClickListener(this);
		nickname_rl.setOnClickListener(this);
		portrait_rl.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.top_img: // 返回
			finish();
			break;
		case R.id.safe_exit: // 安全退出
			SystemUtils.onEvent("Account_Sett_Quit", 1);
			PreferenceUtils.getInstance().clearSharedPreferences(this);
			User.delCurUser();
			setResult(SAFE_EXIT_RESULTCODE);
			finish();
			break;
		case R.id.nickname_rl: // 修改昵称
			Intent intent = new Intent(this, NicknameActivity.class);
			startActivityForResult(intent, NICKNAME_JUMP);
			break;
		case R.id.portrait_rl: // 设置头像
			SystemUtils.onEvent("Account_Sett_Personal_Head", 1);
			showPopupWindow(v);
			break;

		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		User user = CurUserModel.getCurUser();
		if (user == null || user.state != 0) { // 用户不为空且已登陆
			finish();
			return;
		}
		// 手机号
		String phone = PreferenceUtils.getInstance().getPhone(this);
		String front = phone.substring(0, 3);
		String queen = phone.substring(7, 11);
		phone_tv.setText(front + "****" + queen);
		// （设置&修改）昵称
		if (!PreferenceUtils.getInstance().getNickname(this).equals(phone)) {
			set_nickname.setText(PreferenceUtils.getInstance()
					.getNickname(this));
		} else {
			set_nickname.setText("设置");
		}
		// 头像
		ImageLoader.getInstance().displayImage(
				PreferenceUtils.getInstance().getHeadUrl(this), portrait_img);
	}

	/**************
	 * 设置头像对话框
	 * 
	 *************/
	public void showPopupWindow(View v) {
		if (ppw != null) {
			ppw.cancel();
			ppw = null;
		}
		LayoutInflater linflater = LayoutInflater.from(this);
		View view = linflater.inflate(R.layout.setportraitpopupwindow, null);
		dimis = (TextView) view.findViewById(R.id.dimis);
		RelativeLayout dimiss_rl = (RelativeLayout) view
				.findViewById(R.id.dimiss_rl);
		dimiss_rl.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (ppw.isShowing()) {
					ppw.dismiss();
				}
			}
		});
		TextView photograph = (TextView) view.findViewById(R.id.photograph);
		photograph.setOnClickListener(new OnClickListener() { // 拍照

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(
								MediaStore.ACTION_IMAGE_CAPTURE);

						filePath = FileUtils.getKKDHeadIconPath()
								+ System.currentTimeMillis() + ".png";
						intent.putExtra(MediaStore.EXTRA_OUTPUT,
								Uri.fromFile(new File(filePath)));
						PreferenceUtils.putString("headicon", filePath,
								PersonalInformationActivity.this);
						startActivityForResult(intent,
								ImageUtils.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

						ppw.dismiss();// 关闭弹出框
					}
				});
		TextView photo = (TextView) view.findViewById(R.id.photo);
		photo.setOnClickListener(new OnClickListener() { // 相册

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_PICK, null);
				intent.setDataAndType(
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
						ImageUtils.IMAGE_UNSPECIFIED);
				startActivityForResult(intent, ImageUtils.PHOTO_ZOOM);

				ppw.dismiss();// 关闭弹出框
			}
		});
		TextView xiaokuai_Portrait = (TextView) view
				.findViewById(R.id.xiaokuai_Portrait);
		xiaokuai_Portrait.setOnClickListener(new OnClickListener() { // 　使用小快头像

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(
								PersonalInformationActivity.this,
								MyHeadPortraitActivity.class);
						startActivity(intent);
						ppw.dismiss();// 关闭弹出

					}
				});
		dimis.setOnClickListener(new OnClickListener() { // 取消

			@Override
			public void onClick(View v) {
				if (ppw.isShowing()) {
					ppw.dismiss();
				}
			}
		});
		ppw = new KKdDialog(this, R.style.TransparentDialog);
		ppw.setContentView(view);
		ppw.setCanceledOnTouchOutside(true);
		if (ppw.isShowing()) {
			ppw.dismiss();
		} else {
			ppw.show();
		}
	}

	/**
	 * 收缩图片
	 * 
	 * @param uri
	 */
	private String zoomfilePath;

	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");

		zoomfilePath = FileUtils.getKKDHeadIconPath()
				+ System.currentTimeMillis() + ".png";
		intent.putExtra(MediaStore.EXTRA_OUTPUT,
				Uri.fromFile(new File(zoomfilePath)));
		PreferenceUtils.putString("zoomfilePath", zoomfilePath,
				PersonalInformationActivity.this);

		intent.setDataAndType(uri, ImageUtils.IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);

		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 320);
		intent.putExtra("outputY", 320);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, ImageUtils.PHOTO_RESOULT);
	}

	/************************
	 * 图片处理结果
	 ************************/
	public void pictureResult() {
		if (TextUtils.isEmpty(zoomfilePath))
			zoomfilePath = PreferenceUtils.getString("zoomfilePath", "",
					PersonalInformationActivity.this);
		;
		File picture = new File(zoomfilePath);
		if (picture != null) {
			if (picture.exists()) {
				Bitmap bitmap = BitmapFactory.decodeFile(zoomfilePath);// 获取相机返回的数据，并转换为Bitmap图片格式
				if (bitmap != null) {
					String img = ImageUtils.bitmaptoString(bitmap);
					LogUtil.e("img", img);
					ByteArrayOutputStream stream = new ByteArrayOutputStream();
					bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);// 把数据写入文件
					if (mDialog == null)
						mDialog = DialogUtils.toLoadDialog(this, "正在保存...");
					KkdHttpMagager.getInstance().getPhtotoUploadManager(img,
							String.class, new HttpCallBack() {

								@Override
								public void onSuccess(int statusCode,
										Object responseBody) {
									try {
										String responseString = responseBody
												.toString();
										Log.e("response", responseString);
										JSONObject data = new JSONObject(
												responseString);
										LogUtil.e("userHeadUrl",
												data.getString("userHeadUrl"));
										urserHeadUrl = data
												.getString("userHeadUrl");
										PreferenceUtils
												.getInstance()
												.setMyproperty(
														PersonalInformationActivity.this,
														"");
										PreferenceUtils
												.getInstance()
												.setEarnings(
														PersonalInformationActivity.this,
														"");
										PreferenceUtils
												.getInstance()
												.setHeadUrl(
														PersonalInformationActivity.this,
														data.getString("userHeadUrl"));
										mHandler.sendEmptyMessage(UPDATEHEAD_OK);
									} catch (JSONException e) {
										e.printStackTrace();
									}

								}

								@Override
								public void onFailure(int statusCode,
										String desc) {
									PersonalInformationActivity.this.statusCode = statusCode;
									mHandler.sendEmptyMessage(UPDATEHEAD_NO);
								}
							});
				}
			}
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == NICKNAME_JUMP
				&& resultCode == NicknameActivity.PRESERVATION_OK) {
			Toast.makeText(this, "昵称已修改成功", Toast.LENGTH_SHORT).show();
		}
		// 拍照
		if (requestCode == ImageUtils.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
			// 设置文件保存路径
			if (TextUtils.isEmpty(filePath))
				filePath = PreferenceUtils.getString("headicon", "",
						PersonalInformationActivity.this);
			;
			File picture = new File(filePath);
			if (picture != null) {
				if (picture.exists()) {
					startPhotoZoom(Uri.fromFile(picture));
				} else {
				}
			}
		} else if (requestCode == ImageUtils.PHOTO_ZOOM) {
			if (data != null) {
				startPhotoZoom(data.getData());
				LogUtil.e("uri", data.getData().toString());
			}
		}
		if (data == null)
			return;
		// 图片处理结果
		if (requestCode == ImageUtils.PHOTO_RESOULT) {
			pictureResult();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (ppw != null) {
			ppw.cancel();
			ppw = null;
		}
	}
}
